from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import models
from app.db.session import get_db
from app.core.checker import RuleChecker
from app.core.notifier import Notifier
from datetime import datetime
import logging

router = APIRouter()
logger = logging.getLogger(__name__)


@router.post("/trigger/{rule_id}")
def trigger_alert_rule(rule_id: int, db: Session = Depends(get_db)):
    rule = db.query(models.AlertRule).filter(models.AlertRule.id == rule_id).first()
    if not rule:
        raise HTTPException(status_code=404, detail="Rule not found")
    if not rule.is_active:
        raise HTTPException(status_code=400, detail="Rule is not active")
    if rule.origin_db == "Bcenter":
        origin_db = db
    else:
        origin_db = next(get_db(rule.origin_db))
    if  rule.dest_db == "Bcenter":
        dest_db = db
    elif rule.origin_db == rule.dest_db:
        dest_db = origin_db
    else:
        dest_db = next(get_db(rule.dest_db))
    checker = RuleChecker(db,  origin_db,dest_db  )
    notifier = Notifier()

    try:
        triggered, actual_value,standard_value,operator = checker.check_rule(rule)

        if triggered:
            logger.warning(f"手动触发规则: {rule.rule_name}, 当前值: {actual_value}")

            # 发送通知
            success, method = notifier.notify(rule, actual_value)

            # 记录历史
            history = models.AlertHistory(
                rule_id=rule.id,
                rule_name=rule.rule_name,
                actual_value=str(actual_value),
                operator = operator,
                standard_value = str(standard_value),
                notification_flag=triggered,
                notification_sent=success,
                notification_method=method
            )
            db.add(history)

            # 更新最后触发时间
            rule.last_trigger_time = datetime.now()
            db.commit()

            return {
                "status": "triggered",
                "rule_id": rule.id,
                "rule_name": rule.rule_name,
                "actual_value": actual_value,
                "notification_sent": success,
                "notification_method": method
            }
        else:
            # 记录历史
            history = models.AlertHistory(
                rule_id=rule.id,
                rule_name=rule.rule_name,
                actual_value=str(actual_value),
                operator = operator,
                standard_value = str(standard_value),
                notification_flag=triggered,
                notification_sent=0,
                notification_method=''
            )
            db.add(history)
            db.commit()
            return {
                "status": "not_triggered",
                "rule_id": rule.id,
                "rule_name": rule.rule_name,
                "actual_value": actual_value
            }
    except Exception as e:
        logger.error(f"手动触发规则 {rule.rule_name} 时出错: {e}")
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        db.close()
        origin_db.close()
        dest_db.close()